package com.demo.demo.exception.handler;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.alibaba.fastjson.JSONObject;
import com.demo.demo.dto.ExceptionInfo;
import com.demo.demo.exception.AbstractApiException;
import com.demo.demo.exception.BadRequestException;
import com.demo.demo.exception.ForbiddenException;
import com.demo.demo.exception.InternalServerErrorException;
import com.demo.demo.exception.NotFoundException;
import com.demo.demo.exception.UnauthorizedException;

/**
 * 
 * <p>classname:GlobalExceptionHandler</p>
 * <p>Description:</p>
 * <p>Company:斯润天朗</p>
 * @author guogw
 * @version V2.0
 * @date 2018年1月3日 下午6:02:37
 */

@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler({ ForbiddenException.class })
	@ResponseStatus(value = HttpStatus.FORBIDDEN)
	@ResponseBody
	public String handleException(ForbiddenException ex) {
		return toResult(ex);
	}

	@ExceptionHandler({ BadRequestException.class })
	@ResponseStatus(value = HttpStatus.BAD_REQUEST)
	@ResponseBody
	public String handleException(BadRequestException ex) {
		return toResult(ex);
	}

	@ExceptionHandler({ NotFoundException.class })
	@ResponseStatus(value = HttpStatus.NOT_FOUND)
	@ResponseBody
	public String handleException(NotFoundException ex) {
		return toResult(ex);
	}

	@ExceptionHandler({ InternalServerErrorException.class })
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public String handleException(InternalServerErrorException ex) {
		return toResult(ex);
	}

	@ExceptionHandler({ UnauthorizedException.class })
	@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
	@ResponseBody
	public String handleException(UnauthorizedException ex) {
		return toResult(ex);
	}

	private String toResult(AbstractApiException ex) {
		return JSONObject.toJSONString(new ExceptionInfo<String>(ex.getCode(), ex.getMessage(), ""));
	}

}